import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Balloon, Divider } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { Header, Body, BodyContent, Content, SearchIcon, YunxiaoList } from '@alife/devops-ui';
import CreateTagModal from './createTagModal';
import ListEmpty from 'atComponents/ListEmpty';
import TagSkeleton from 'components/skeleton/tag';
import TagInfoMedia from './tagInfoMedia';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import AccessContainer from 'components/accessContainer';
import { enterPage, Perf } from 'utils/track';
import * as actions from '../actions/index';
import * as rootActions from 'pages/index/actions';
import debounce from 'lodash.debounce';
import KEYCODE from 'utils/keycode';
import { ENUM } from 'utils/constants';
import utils from 'utils';
import intl from '../../../../../../../locale';

const { ctrlKey } = ENUM.getOSKeyMap();

class Root extends Component {
  constructor(props) {
    super(props);
    this.onTagSearch = debounce(this.onTagSearch, 500);
    this.state = {
      search: '',
    };
  }

  componentDidMount() {
    this.props.loadPage(1);
    const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
    if (isTooLarge && document.getElementById('container')) {
      document.getElementById('container').classList.add('has-too-large-tip');
    }
    enterPage('Repo-Tags', {
      sendPerf: false,
    });

    document.addEventListener('keydown', this.handleKeyCodeEvent);
  }

  handleKeyCodeEvent = (e) => {
    // ctrl + / 进行搜索
    if (e[ctrlKey] && e.keyCode === KEYCODE.SPLIT) {
      document.querySelector('.search-ctrl>button').click();
      document.querySelector('.search-ctrl input').focus();
    }
  };

  componentDidUpdate(prevProps) {
    if (prevProps.repoSize !== this.props.repoSize) {
      const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
      if (isTooLarge && document.getElementById('container')) {
        document.getElementById('container').classList.add('has-too-large-tip');
      }
    }
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyCodeEvent);
    if (document.getElementById('container')) {
      document.getElementById('container').classList.remove('has-too-large-tip');
    }
  }

  onPageNoChange = (page) => {
    this.props.loadPage(page);
  };

  onPageSizeChange = (pageSize) => {
    this.props.updateData({
      pageSize,
    });

    this.props.loadPage(1, {
      per_page: pageSize,
    });
  };

  onTagSearch = (value) => {
    this.setState({
      search: value,
    });

    this.props.loadPage(1, value);
  };

  onCommitChange = () => {};

  getMediaListJsx() {
    const { tags, isLoading } = this.props;
    const { search } = this.state;

    if (isLoading) {
      return <TagSkeleton />;
    }

    if (tags && tags.length) {
      return (
        <>
          <Perf page="Repo-Tags" />
          <YunxiaoList
            dataSource={tags}
            renderItem={(tag) => (
              <TagInfoMedia
                tag={tag}
                remove={this.props.remove}
                onChange={this.onCommitChange}
                {...this.props}
              />
            )}
          />
        </>
      );
    }
    if (search) {
      return (
        <ListEmpty
          fullPage
          type="project"
          className="no-btns"
          description={
            <span>
              <Perf page="Repo-Tags" />
              {intl.get({
                id: 'code-assets.projectTags.containers.root.NoSearchResults',
                defaultMessage: '搜索无结果',
              })}
            </span>
          }
          imgType="search"
        />
      );
    }
    return (
      <ListEmpty
        fullPage
        type="project"
        className="project-tag-empty"
        image={'https://img.alicdn.com/tfs/TB1_LIuzrr1gK0jSZR0XXbP8XXa-600-602.png'}
        content="暂未创建标签"
        description={
          <div className="tag-empty">
            <Perf page="Repo-Tags" />
            <div className="tag-empty-text">通过标签记录代码库重要版本</div>
            <div className="tag-empty-text">
              {"同时支持通过 git 命令创建标签：git tag -a v1.0 -m '版本 1.0'"}
            </div>
          </div>
        }
      />
    );
  }

  render() {
    const { role, isArchive } = window.FORCE.pathResource;
    const { lastMirrorSyncRecord, total, currentPage } = this.props;
    let isMirrorSynchronizing = false;
    if (lastMirrorSyncRecord) {
      isMirrorSynchronizing = utils.isMirrorSynchronizing(lastMirrorSyncRecord.sync_status);
    }
    return (
      <>
        <Header
          title={intl.get({
            id: 'code-assets.projectTags.containers.root.Label',
            defaultMessage: '标签',
          })}
          operation={
            <div>
              <SearchIcon
                placeholder={intl.get({
                  id: 'code-assets.projectTags.containers.root.EnterATagName',
                  defaultMessage: '输入标签名称',
                })}
                direction="rtl"
                onChange={this.onTagSearch}
                style={{ width: 240 }}
                className="search-ctrl"
              />
              {isArchive === 'false' && !isMirrorSynchronizing ? (
                <AccessContainer neededRole={PROJECT_WRITE_ROLES} role={role}>
                  <Divider direction="ver" />
                  <CreateTagModal
                    trigger={
                      <Button type="primary" onClick={this.onDialogOpen}>
                        {intl.get({
                          id: 'code-assets.projectTags.containers.root.CreateTag',
                          defaultMessage: '新建标签',
                        })}
                      </Button>
                    }
                    {...this.props}
                  />
                </AccessContainer>
              ) : null}
              {isArchive === 'false' && isMirrorSynchronizing && (
                <>
                  <Divider direction="ver" />
                  <Balloon.Tooltip
                    trigger={
                      <Button type="primary" disabled style={{ marginLeft: 16 }}>
                        {intl.get({
                          id: 'code-assets.projectTags.containers.root.CreateTag',
                          defaultMessage: '新建标签',
                        })}
                      </Button>
                    }
                    align="t"
                    text={intl.get({
                      id: 'code-assets.projectTags.containers.root.TheRepositoryIsBeingSynchronized',
                      defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
                    })}
                  />
                </>
              )}
            </div>
          }
        />
        <Body>
          <BodyContent>
            <Content>{this.getMediaListJsx()}</Content>
            <Pagination
              onChange={this.onPageNoChange}
              onPageSizeChange={this.onPageSizeChange}
              pageSize={this.props.pageSize}
              current={currentPage}
              total={total}
            />
          </BodyContent>
        </Body>
      </>
    );
  }
}

export default connect(
  (state) => ({
    ...state.project.projectTags,
    pageInfo: state.root.pageInfo,
    lastMirrorSyncRecord: state.project.root.lastMirrorSyncRecord,
  }),
  (dispatch) => bindActionCreators({ ...actions, ...rootActions }, dispatch),
)(Root);
